/**
 * Created by ChenKai on 2018/03/15.
 */

'use strict'

import axios from 'axios'

let baseURL = ''

// 拦截模式
let defaultMode = {
  intercept: true,
  showLoading: true,
  showToast: true,
  showMask: true,
  needLogin: true
}

// create a new instance of axios with a custom config
const instance = axios.create({
  baseURL: baseURL,
  timeout: 10000,
  headers: {
    post: {
      'Content-Type': 'application/json;charset=UTF-8;'
    }
  }
})

// 请求拦截器
instance.interceptors.request.use(function (config) {
  // config.mode.showLoading && (window.$vm.loading = '加载中...')
  return config
}, function (error) {
  console.error('request error intercepted:', error)
  // window.$vm.loading = false
  return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(function (response) {
  // const mode = response.config.mode
  // window.$vm.loading = false
  return response
}, function (error) {
  return Promise.reject(error)
})

export default function fetch (opt, mode) {
  const config = {}
  config.url = opt.url
  config.method = opt.method
  if (typeof opt.timeout === 'number') {
    config.timeout = opt.timeout
  }
  if (opt.query) {
    if (config.method === 'get') {
      config.params = opt.query
    } else {
      config.data = opt.query
    }
  }
  if (opt.headers) {
    config.headers = Object.assign({}, instance.defaults.headers, opt.headers)
  }
  !mode && (mode = {})
  config.mode = Object.assign({}, defaultMode, mode)
  return new Promise((resolve, reject) => {
    instance.request(config)
      .then(response => {
        const res = response.data
        if (res.success) {
          resolve(res.data, response)
        } else {
          reject(res)
        }
      }, err => {
        reject(err)
      })
      .catch((error) => { // 其他未捕获的异常
        reject(error)
      })
  })
}
